<template>
  <div>
    <el-form
      label-width="240px"
    >
      <el-form-item :label="$t('appId')">
        <el-input v-model="companyConfigWxApp.appId" />
      </el-form-item>
      <el-form-item :label="$t('appSecret')">
        <el-input v-model="companyConfigWxApp.appSecret" />
      </el-form-item>
      <el-form-item :label="$t('save')">
        <el-button type="warning" @click="getWxAppToken">{{ $t('wxApp')+$t('token') }}</el-button>
        <el-button type="primary" @click="updateCompanyConfigWxApp">{{ $t('confirm') }}</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      :visible.sync="dialogTokenVisible"
    >
      <el-form>
        <el-form-item :label="$t('outTime')">
          <el-input v-model="outTime" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('accessToken')">
          <el-input v-model="accessToken" :disabled="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogTokenVisible = false">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { successNotice, formatDate } from '@/util/common'
import { getToken } from '@/api/iot/iotThirdPartyTokenApi'
import {
  getCompanyConfigWxApp,
  updateCompanyConfigWxApp
} from '@/api/iot/iotCompanyConfigWxAppApi'
export default {
  name: 'IotWxApp',
  props: {
    companyId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      companyConfigWxApp: {},
      dialogTokenVisible: false,
      outTime: null,
      accessToken: null
    }
  },
  created() {
    this.getCompanyConfigWxApp()
  },
  methods: {
    getCompanyConfigWxApp() {
      getCompanyConfigWxApp({
        companyId: this.companyId
      }).then(res => {
        const { data } = res
        if (data) {
          this.companyConfigWxApp = data
        }
      })
    },
    updateCompanyConfigWxApp() {
      updateCompanyConfigWxApp({
        ...this.companyConfigWxApp,
        companyId: this.companyId
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
          this.getCompanyConfigWxApp()
        }
      })
    },
    getWxAppToken() {
      getToken({
        'companyId': this.companyId,
        'type': 'wxApp'
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.outTime = formatDate(this, data.outTime)
          this.accessToken = data.accessToken
          this.dialogTokenVisible = true
        }
      })
    }
  }
}
</script>

